import uniq from 'lodash/uniq';
import { createRouter, createWebHistory } from 'vue-router';

// const env = import.meta.env.MODE || 'development';

// 导入page相关固定路由
const defaultModules = import.meta.glob('./modules/**/defaultRouter.ts', {
  eager: true,
});

// 存放固定路由
export const defaultRouterList = mapModuleRouterList(defaultModules);

export const allRoutes = [...defaultRouterList];

// 固定路由模块转换为路由
export function mapModuleRouterList(modules) {
  const routerList = [];
  Object.keys(modules).forEach(key => {
    // @ts-ignore
    const mod = modules[key].default || {};
    const modList = Array.isArray(mod) ? [...mod] : [mod];
    routerList.push(...modList);
  });
  return routerList;
}

export const getRoutesExpanded = () => {
  const expandedRoutes = [];
  return uniq(expandedRoutes);
};

export const getActive = (maxLevel = 3) => {
  // 非组件内调用必须通过Router实例获取当前路由
  const route = router.currentRoute.value;

  if (!route.path) {
    return '';
  }

  return route.path
    .split('/')
    .filter((_item, index) => index <= maxLevel && index > 0)
    .map(item => `/${item}`)
    .join('');
};

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_BASE_URL),
  routes: allRoutes,
  scrollBehavior() {
    return {
      el: '#app',
      top: 0,
      behavior: 'smooth',
    };
  },
});

export default router;
